package com.example.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

public class BtnEventActivity extends AppCompatActivity {
  ImageView imageView;
  @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.btn_listener_layout);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("基于回调");
    setSupportActionBar(toolbar);
    imageView = (ImageView) findViewById(R.id.Img);
    SetOnTouchEvent();

  }

  @Override public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(0, 1, 0, "返回上一级");

    return true;
  }

  @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()) {
      case 1:
        BackToLastLevel();
        break;

    }
    return true;
  }

  private void BackToLastLevel() {
    Intent intent = new Intent(this, BtnListenActivity.class);
    startActivity(intent);
  }
  private void SetOnTouchEvent() {
    imageView.setOnTouchListener(new View.OnTouchListener() {
      private float dX;
      private float dY;
      @Override public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
          case MotionEvent.ACTION_DOWN:
            //按下时
            dX = v.getX() - event.getRawX();
            dY = v.getY() - event.getRawY();

            break;
          case MotionEvent.ACTION_MOVE:
            imageView.setX(event.getRawX() + dX);
            imageView.setY(event.getRawY() + dY);
            break;
          case MotionEvent.ACTION_UP:
            //离开时
            break;
        }
        return true;
      }

    });
  }
}
